package com.dtjd.playcoinmonkey.activities.main;

import android.app.ActivityOptions;
import android.content.Intent;
import android.os.Bundle;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.core.view.ViewCompat;
import androidx.fragment.app.Fragment;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAdSdk;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;
import com.dtjd.playcoinmonkey.MyApplication;
import com.dtjd.playcoinmonkey.R;
import com.dtjd.playcoinmonkey.activities.NoticeActivity;
import com.dtjd.playcoinmonkey.activities.PostDetailActivity;
import com.dtjd.playcoinmonkey.activities.PublishActivity;
import com.dtjd.playcoinmonkey.activities.SearchActivity;
import com.dtjd.playcoinmonkey.adapter.HomeListAdapter;
import com.dtjd.playcoinmonkey.bean.HomeListBean;
import com.dtjd.playcoinmonkey.bean.HttpParaBean;
import com.dtjd.playcoinmonkey.databinding.FragmentHomeBinding;
import com.dtjd.playcoinmonkey.utils.Network;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class HomeFragment extends Fragment {
    private FragmentHomeBinding binding;
    private HomeListAdapter adp;
    private final List<HomeListBean> data=new ArrayList<>();
    private int current=1;
    private MainActivity activity;
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentHomeBinding.inflate(inflater, container, false);
        activity= (MainActivity) requireActivity();
        adp=new HomeListAdapter(activity, data, (v, position) -> { }, (v, position) -> { }, (v, position) -> { });
        binding.homeRefresh.setRefreshHeader(new ClassicsHeader(activity));
        binding.homeRefresh.setRefreshFooter(new ClassicsFooter(activity));
        binding.homeRefresh.setOnRefreshListener(refreshLayout -> {
            current=1;
            refresh(refreshLayout,null);
        });
        binding.homeRefresh.setOnLoadMoreListener(refreshLayout -> refresh(null,refreshLayout));
        binding.homePost.setOnClickListener(view -> publish());
        binding.homeFloating.setOnClickListener(view ->publish());
        binding.homeDetail.setOnClickListener(view -> startActivity(new Intent(activity, NoticeActivity.class).putExtra("title",getResources().getString(R.string.warn)).putExtra("isWarn",true)));
        binding.homeList.setAdapter(adp);
        binding.homeList.setOnItemClickListener((adapterView, view, i, l) -> {
            if (view.findViewById(R.id.item_home_title)==null)return;
            if (view.findViewById(R.id.item_home_account)==null)return;
            Pair<View,String> pair1 = new Pair<>(view.findViewById(R.id.item_home_title), ViewCompat.getTransitionName(view.findViewById(R.id.item_home_title)));
            Pair<View,String> pair2 = new Pair<>(view.findViewById(R.id.item_home_account),ViewCompat.getTransitionName(view.findViewById(R.id.item_home_account)));
            MyApplication.postBean=data.get(i);
            startActivity(new Intent(activity, PostDetailActivity.class),ActivityOptions.makeSceneTransitionAnimation(activity,pair1,pair2).toBundle());
        });
        binding.homeSearch.setOnClickListener(view -> startActivity(new Intent(activity, SearchActivity.class),ActivityOptions.makeSceneTransitionAnimation(activity, binding.homeSearch, "search").toBundle()));
        List<HttpParaBean> para=new ArrayList<>();
        para.add(new HttpParaBean("getOne","true"));
        Network.post(para, "wbhMain/getWarn", new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) { e.printStackTrace(); }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {
                activity.runOnUiThread(() -> {
                    try {
                        JSONArray ja = new JSONObject(Objects.requireNonNull(response.body()).string()).getJSONArray("datalist");
                        if (ja.length()>0) binding.homeWarn.setText(ja.getJSONObject(0).getString("content"));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    refresh(null,null);
                });
            }
        });
        return binding.getRoot();
    }
    private void publish() {
        startActivity(new Intent(activity, PublishActivity.class));
    }
    private void refresh(RefreshLayout refreshLayout,RefreshLayout loadmorelayout) {
        solution2(refreshLayout, loadmorelayout);
    }
    public void solution1(RefreshLayout refreshLayout,RefreshLayout loadmorelayout){
        TTAdNative mTTAdNative = TTAdSdk.getAdManager().createAdNative(activity);
        AdSlot adSlot = new AdSlot.Builder().setCodeId("946910815").setSupportDeepLink(true).setAdCount(1).setExpressViewAcceptedSize(350,0).build();
        mTTAdNative.loadNativeExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
            @Override
            public void onError(int code, String message) {   }
            @Override
            public void onNativeExpressAdLoad(List<TTNativeExpressAd> ads) {
                if (loadmorelayout!=null&&refreshLayout==null) current++;
                ArrayList<HttpParaBean> list=new ArrayList<>();
                list.add(new HttpParaBean("current",String.valueOf(current)));
                list.add(new HttpParaBean("size", "8"));
                list.add(new HttpParaBean("token", ""));
                Network.post(list, "wbhMain/getPosts", new Callback() {
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                        e.printStackTrace();
                    }
                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) {
                        activity.runOnUiThread(() -> {
                            try {
                                JSONObject jo1=new JSONObject(Objects.requireNonNull(response.body()).string());
                                JSONArray ja = jo1.getJSONArray("datalist");
                                if (ja.length()!=0){
                                    if (loadmorelayout==null) data.clear();
                                    for (int i = 0; i < ja.length(); i++) {
                                        JSONObject jo = ja.getJSONObject(i);
                                        JSONArray jo_imgs = jo.getJSONArray("imgs");
                                        String img_url="";
                                        if (jo_imgs.length()>0) img_url= jo_imgs.getString(0);
                                        String bannedCount = "0";
                                        if (jo.has("bannedCount")) bannedCount=jo.getString("bannedCount");
                                        data.add( new HomeListBean(0,jo.getString("bp_content"), img_url, jo.getString("bp_report"), jo.getString("bp_sort"), jo.getString("bp_title"), jo.getString("bp_type"), jo.getInt("bu_id"), jo.getString("id"), jo.getInt("bp_click_number"), jo.getString("time"), jo.getString("wb_nickname"), jo.getString("wb_url"),bannedCount,null));
                                    }
                                    data.add(data.size()-3, new HomeListBean(5,"","","","","","",0,"",0,"","","","",ads.get(0)));
                                    adp.notifyDataSetChanged();
                                }
                                if (refreshLayout!=null)refreshLayout.finishRefresh(0);
                                if (loadmorelayout!=null)loadmorelayout.finishLoadMore(0);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        });
                    }
                });
            }
        });
    }
    public void solution2(RefreshLayout refreshLayout,RefreshLayout loadmorelayout){
        if (loadmorelayout!=null&&refreshLayout==null) current++;
        ArrayList<HttpParaBean> list=new ArrayList<>();
        list.add(new HttpParaBean("current",String.valueOf(current)));
        list.add(new HttpParaBean("size", "8"));
        list.add(new HttpParaBean("token", ""));
        Network.post(list, "wbhMain/getPosts", new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                e.printStackTrace();
            }
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {
                activity.runOnUiThread(() -> {
                    try {
                        JSONObject jo1=new JSONObject(Objects.requireNonNull(response.body()).string());
                        JSONArray ja = jo1.getJSONArray("datalist");
                        if (ja.length()!=0){
                            if (loadmorelayout==null) data.clear();
                            for (int i = 0; i < ja.length(); i++) {
                                JSONObject jo = ja.getJSONObject(i);
                                JSONArray jo_imgs = jo.getJSONArray("imgs");
                                String img_url="";
                                if (jo_imgs.length()>0) img_url= jo_imgs.getString(0);
                                String bannedCount = "0";
                                if (jo.has("bannedCount")) bannedCount=jo.getString("bannedCount");
                                data.add( new HomeListBean(0,jo.getString("bp_content"), img_url, jo.getString("bp_report"), jo.getString("bp_sort"), jo.getString("bp_title"), jo.getString("bp_type"), jo.getInt("bu_id"), jo.getString("id"), jo.getInt("bp_click_number"), jo.getString("time"), jo.getString("wb_nickname"), jo.getString("wb_url"),bannedCount,null));
                            }
                            data.add(data.size()-3, new HomeListBean(5,"","","","","","",0,"",0,"","","","","have"));
                            adp.notifyDataSetChanged();
                        }
                        if (refreshLayout!=null)refreshLayout.finishRefresh(0);
                        if (loadmorelayout!=null)loadmorelayout.finishLoadMore(0);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
        });
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}